package dao.impl;

import java.util.List;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.Transaction;

import dao.ArticleTypeDao;
import domain.ArticleType;

public class ArticleTypeImpl implements ArticleTypeDao {

	public boolean deleteArticleType(ArticleType at) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateSessionFactory.getSession();
			tx = s.beginTransaction();
			s.delete(at);
			s.flush();
			tx.commit();
			return true;
		} finally {
			if (s != null)
				s.close();
		}
	}

	public List findAllArticleTypeByPage(int pageNo, int pageSize) {
		Session s = null;
		try {
			s = HibernateSessionFactory.getSession();
			int offset=(pageNo-1)*pageSize;
			String hql = "from ArticleType as at order by at.id";
			return s.createQuery(hql).setFirstResult(offset).setMaxResults(pageSize).list();
		} finally {
			if (s != null)
				s.close();
		}
	}

	public ArticleType findArticleTypeById(int id) {
		Session s = null;
		try {
			s = HibernateSessionFactory.getSession();
			ArticleType at = (ArticleType) s.get(ArticleType.class, id);
			return at;
		} finally {
			if (s != null)
				s.close();
		}
	}

	public long findCount() {
		Session s = null;
		try {
			s = HibernateSessionFactory.getSession();
			String hql = "select count(at.id) from ArticleType as at";
			Object obj= s.createQuery(hql).uniqueResult();
			return (Long)obj;
		} finally {
			if (s != null)
				s.close();
		}
	}

	public boolean saveArticleType(ArticleType at) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateSessionFactory.getSession();
			tx = s.beginTransaction();
			s.save(at);
			tx.commit();
			return true;
		} finally {
			if (s != null)
				s.close();
		}
	}

	public boolean updateArticleType(ArticleType at) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateSessionFactory.getSession();
			tx = s.beginTransaction();
			s.update(at);
			tx.commit();
			return true;
		} finally {
			if (s != null)
				s.close();
		}
	}

	public List findAllArticleType() {
		Session s = null;
		try {
			s = HibernateSessionFactory.getSession();
			String hql = "from ArticleType as at order by at.id";
			return s.createQuery(hql).list();
		} finally {
			if (s != null)
				s.close();
		}
	}

	public Set findAllArticleByTypeByPage(int articleType_Id) {
		Session s = null;
		try {
			s = HibernateSessionFactory.getSession();
			ArticleType at = (ArticleType) s.get(ArticleType.class, articleType_Id);
			//Hibernate.initialize(at.getArticles());
			Set articleSet=at.getArticles();
			return articleSet;
		} finally {
			if (s != null)
				s.close();
		}
	}

}
